// utils/mathjaxRenderer.ts
import { mathjax } from 'mathjax-full/js/mathjax'
import { TeX } from 'mathjax-full/js/input/tex'
import { SVG } from 'mathjax-full/js/output/svg'
import { liteAdaptor } from 'mathjax-full/js/adaptors/liteAdaptor'
import { RegisterHTMLHandler } from 'mathjax-full/js/handlers/html'

// 初始化MathJax
const adaptor = liteAdaptor()
RegisterHTMLHandler(adaptor)

const tex = new TeX({
  packages: ['base', 'ams', 'autoload', 'require', 'newcommand', 'begingroup'],
  inlineMath: [              // 添加这个配置
    ['\\(', '\\)']           // 识别 \(...\)
  ],
  displayMath: [             // 添加这个配置
    ['\\[', '\\]']           // 识别 \[...\]
  ],
  processEscapes: true       // 允许使用 \$ 等转义字符
})
const svg = new SVG({
  fontCache: 'global',
})

const html = mathjax.document('', {
  InputJax: tex,
  OutputJax: svg,
})

// 增强的公式识别正则表达式
const MATH_REGEX = /(\$\$[^$]+\$\$|\$[^$]+\$|\\\(.*?\\\)|\\\[.*?\\\]|\\begin\{.*?\}.*?\\end\{.*?\})/gs

export function renderAllMathInText(text) {
  let result = ''
  let lastIndex = 0
  let match
  
  while ((match = MATH_REGEX.exec(text)) !== null) {
    // 添加前面的普通文本
    if (match.index > lastIndex) {
      result += text.substring(lastIndex, match.index)
    }
    
    // 处理匹配到的公式
    try {
      const displayMode = match[0].startsWith('$$') || 
                         match[0].startsWith('\\[') || 
                         match[0].startsWith('\\begin')
      
      // 预处理公式 - 替换 \( \) 为 $ $
      let formula = match[0]
      if (formula.startsWith('\\(') && formula.endsWith('\\)')) {
        formula = '$' + formula.slice(2, -2) + '$'
      } else if (formula.startsWith('\\[') && formula.endsWith('\\]')) {
        formula = '$$' + formula.slice(2, -2) + '$$'
      }
      
      const node = html.convert(formula, { display: displayMode })
      result += adaptor.innerHTML(node)
    } catch (e) {
      console.error('公式渲染错误:', e)
      result += match[0] // 保留原始公式如果渲染失败
    }
    
    lastIndex = match.index + match[0].length
  }
  
  // 添加剩余的普通文本
  if (lastIndex < text.length) {
    result += text.substring(lastIndex)
  }
  
  return result
}
